
import { ecs } from "db://oops-framework/libs/ecs/ECS";
import { Scene } from "../Scene";
import { RoleAttributeType, RoleModuleType } from "../../../role/model/RoleEnum";
import { find } from "cc";
import { BattleResultType } from "../model/BattleEnum";

/**
 * 加载战斗双方武将动画
 */
@ecs.register('LoadBattleRoles')
export class LoadBattleRolesComp extends ecs.Comp {
    /** 1: 人跟怪，2: 人， 3：怪 */
    public loadType: number = 1;
    reset() {
        this.loadType = 1;
    }
}

export class LoadBattleRolesSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    private num: number = 0;
    private loadedNum: number = 0;
    filter(): ecs.IMatcher {
        return ecs.allOf(LoadBattleRolesComp);
    }

    entityEnter(e: Scene): void {
        this.loadedNum = 0;

        if (e.LoadBattleRoles.loadType == 1) {
            this.num = e.MapModelRole.roles.length;
            this.setRoles(e);
            this.setEnemys(e);
        } else if (e.LoadBattleRoles.loadType == 2) {
            this.num = e.MapModelRole.friends.length;
            this.setRoles(e);
        } else {
            this.num = e.MapModelRole.enemys.length;
            this.setEnemys(e);
        }
    }
    /** 设置角色 */
    private setRoles(e: Scene) {
        var mmr = e.MapModelRole;
        // 显示我方角色
        mmr.friends.forEach(r => {
            r.setNumericValue(RoleAttributeType.hp_battle, RoleModuleType.Battle, r.hp);
            var node = find(`map/game/friend${r.RoleModel.pos}`, e.MapView.node)!;
            r.loadByBattle(node);
            r.right();
            this.loadedNum += 1;
            this.battleStart(e);
        });
    }
    /** 设置怪物 */
    private setEnemys(e: Scene) {
        var mmr = e.MapModelRole;
       // 显示敌方角色
       mmr.enemys.forEach(r => {
        r.setNumericValue(RoleAttributeType.hp_battle, RoleModuleType.Battle, r.hp);
        var node = find(`map/game/enemy${r.RoleModel.pos}`, e.MapView.node)!;
        r.loadByBattle(node);
        r.left();
        this.loadedNum += 1;
        this.battleStart(e);
    });
    }
    private battleStart(e: Scene) {
        if(this.loadedNum == this.num){
            e.setEnemysTotalHp(1);
            e.BattleModel.battleResultType = BattleResultType.Battling;
            if(e.MapModelRole.friends.length > 0){
                e.battleStart();
            }
            e.remove(LoadBattleRolesComp);
        }

    }
}